<template>
	<view class="content">
		<view class="head_button">
			<navigator url="../index/all"  hover-class="navigator-hover">
			<view class="button_item">
				<image src="../../static/icon/icon-1.png" mode=""></image>
				<view class="button_text">
					全部房源
				</view>
			</view>
			</navigator>
			<view class="button_item" >
				<image src="../../static/icon/icon-2.png" mode="" @click="getLocation"></image>
				<view class="button_text">
					附近房源
				</view>
			</view>
			<navigator url="../index/mine"  hover-class="navigator-hover">
			<view class="button_item">	
				<image src="../../static/icon/icon-3.png" mode=""></image>
				<view class="button_text">
					我的房源
				</view>
			</view>
			</navigator>
		</view>
		<view class="Popular">
			<view class="pop_title">
				热门推荐
			</view>
			<view class="pop_content">
				
				<navigator v-for="(item,index) in hotList" :key="index" :url="'../me/content/houseDetail?house_id='+item.id"  hover-class="navigator-hover">
				<view class="pop_item" >
					<view class="left">
						<!-- {{item.pic}} -->
						
						<image v-if="item.image" :src="siteUrl+item.image"  mode="scaleToFill"></image>
						
						
						<image v-else :src="siteUrl+item.images.split(',',1)"  mode="scaleToFill"></image>
						
						
						
						
					</view>
					<view class="right">
						<view class="name">{{item.title}}</view>
						<view class="address">{{item.location_near}}</view>
						<!--<view class="tags" >
							<text class="tag" v-for="(tag,ind) in item.tags" :key="ind">{{tag}}</text>
						</view>-->
						<view class="prices">
							
						
							<view :style="{color:(item.status==1?'#999999':'#FF4C4C')}" >{{item.price}}元/月</view>
							
							<view :style="{display:(item.status==1?'block':'none')}" class="existence">已租</view>
							
							
						</view>
						
					</view>
				</view>
				</navigator>
				<uni-load-more  :loadingType="loadingType" :contentText="contentText" :status="status"></uni-load-more>
			</view>
		</view>
		
		
		<uni-popup :show="type === 'showpopup'" mode="fixed" @hidePopup="togglePopup('')">
		    <view class="popup-view">
		        <text class="popup-title">需要用户授权位置权限</text>
		        <view class="uni-flex popup-buttons">
		            <button class="uni-flex-item" type="primary" open-type="openSetting" @tap="openSetting">设置</button>
		            <button class="uni-flex-item" @tap="togglePopup('')">取消</button>
		        </view>
		    </view>
		</uni-popup>	
			
	</view>
</template>

<script>
	var _self,
	page = 1,
	timer = null;
	import mpopup from '../../components/xuan-popup/xuan-popup.vue'
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	var util = require('../../common/util.js');
	var formatLocation = util.formatLocation;
	// #ifdef APP-PLUS
	import permision from "@/common/permission.js"
	// #endif
	
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
	export default {
		components: {
		   uniPopup,uniLoadMore
		},		
		data() {
			return {
				siteUrl:this.websiteUrl,
				status: 'more',
				loadingText: '加载中...',
				loadingType: 2,//定义加载方式 0---contentdown  1---contentrefresh 2---contentnomore
				contentText: {
				    contentdown:'上拉显示更多',
				    contentrefresh: '正在加载...',
				    contentnomore: '没有更多数据了'
				},
				location: {},
				type: '',
				keywords:'',
				hasLocation: false,
				title: 'getLocation',
				hotList:[
					{						
						url:'/detail/',
						pic:'../../static/img/room1.png',
						name:'沙园复式一房一厅，两层',
						address:'3号线客村站 200米',
						tags:['一房一厅','免半月租'],
						price:'1800',
						isActive:true
					},
					{
						url:'/detail/',
						pic:'../../static/img/room1.png',
						name:'沙园复式一房一厅，两层',
						address:'3号线客村站 200米',
						tags:['一房一厅','免半月租'],
						price:'1800',
						isActive:false
					}
				],
				
			}
		},
		onLoad(){
			_self = this;
			this.gethotList();
		},
		onPullDownRefresh: function() {
			//下拉刷新的时候请求一次数据
		    this.gethotList()					
		},
		onReachBottom: function() {
			//触底的时候请求数据，即为上拉加载更多
			//为了更加清楚的看到效果，添加了定时器
		    if (timer != null) {
		        clearTimeout(timer);
		    }
		   // timer = setTimeout(function() {
		       // _self.getmorenews();
		   // }, 2000);					
			// 正常应为:
			 _self.getmorenews();
		},
		methods: {
			
			togglePopup(type) {
			        this.type = type;
			    },
			    showConfirm() {
			        this.type = 'showpopup';
			    },
			    hideConfirm() {
			        this.type = '';
			    },
			    async getLocation() {
			        // #ifdef APP-PLUS
			        let status = await this.checkPermission();
			        if (status !== 1) {
			            return;
			        }
			        // #endif
			        // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
			        let status = await this.getSetting();
			        if (status === 2) {
			            this.showConfirm();
			            return;
			        }
			        // #endif
			        this.doGetLocation();				
			    },
			    doGetLocation() {
			        uni.getLocation({
			            success: (res) => {
			                this.hasLocation = true;
			                this.location = formatLocation(res.longitude, res.latitude);
					
							 //var lon = parseFloat(this.location.longitude[0])+parseFloat(this.location.longitude[1]/60)
							 //var lat = parseFloat(this.location.latitude[0])+parseFloat(this.location.latitude[1]/60)							 							 
							 var lon = res.longitude
							 var lat = res.latitude
							 
							 
							 uni.navigateTo({
							 		url: "/pages/index/near?lon="+lon+"&lat="+lat
							 });
							 
							
			            },
			            fail: (err) => {
			                // #ifdef MP-BAIDU
			                if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
			                    this.showConfirm();
			                }
			                // #endif
			                // #ifndef MP-BAIDU
			                if (err.errMsg.indexOf("auth deny") >= 0) {
			                    uni.showToast({
			                        title: "访问位置被拒绝"
			                    })
			                } else {
			                    uni.showToast({
			                        title: err.errMsg
									//title: "请检查手机定位服务是否开启"
			                    })
			                }
			                // #endif
			            }
			        })
			    },
			    getSetting: function() {
			        return new Promise((resolve, reject) => {
			            uni.getSetting({
			                success: (res) => {
			                    if (res.authSetting['scope.userLocation'] === undefined) {
			                        resolve(0);
			                        return;
			                    }
			                    if (res.authSetting['scope.userLocation']) {
			                        resolve(1);
			                    } else {
			                        resolve(2);
			                    }
			                }
			            });
			        });
			    },
			    openSetting: function() {
			        this.hideConfirm();
			        uni.openSetting({
			            success: (res) => {
			                if (res.authSetting && res.authSetting['scope.userLocation']) {
			                    this.doGetLocation();
			                }
			            },
			            fail: (err) => {}
			        })
			    },
			    async checkPermission() {
			        let status = permision.isIOS ? await permision.requestIOS('location') :
			            await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
			
			        if (status === null || status === 1) {
			            status = 1;
			        } else if (status === 2) {
			            uni.showModal({
			                content: "系统定位已关闭",
			                confirmText: "确定",
			                showCancel: false,
			                success: function(res) {
			                }
			            })
			        } else if (status.code) {
			            uni.showModal({
			                content: status.message						
			            })
			        } else {
			            uni.showModal({
			                content: "需要定位权限",
			                confirmText: "设置",
			                success: function(res) {
			                    if (res.confirm) {
			                        permision.gotoAppSetting();
			                    }
			                }
			            })
			        }
			
			        return status;
			    },
			    clear: function() {
			        this.hasLocation = false
			    },
				
			getmorenews: function() {			  
				if(_self.status !== 'more'){
					return false
				}						    
				_self.status = 'loading'
			    uni.showNavigationBarLoading();//显示加载动画
			    uni.request({
			        url:this.websiteUrl+'/api.php/house/houseList?page='+page,
			        method: 'POST',
			        header: {
			        	'content-type':'application/x-www-form-urlencoded'				
			        },
			        data: {action:'hot',keywords:this.keywords},
			        success: function(res) {			          																		
			            if (res.data.data.data.length == 0) {//没有数据			                
							_self.status = 'noMore'
							
			                uni.hideNavigationBarLoading();//关闭加载动画							
			                return false;
			            }
			            page++;//每触底一次 page +1										
			            _self.hotList = _self.hotList.concat(res.data.data.data);//将数据拼接在一起			        
						_self.status = 'more'					
			            uni.hideNavigationBarLoading();//关闭加载动画
			        }
			    });
			},
			gethotList(){
				page = 1;				
				_self.status = 'more'
				uni.showNavigationBarLoading();	
				uni.request({
					url: this.websiteUrl+'/api.php/house/houseList?page=1',
					method: 'POST',
					header: {
						'content-type':'application/x-www-form-urlencoded'				
					},
					data: {action:'hot',keywords:this.keywords},
					success:function(res){
						console.log(res)
						page++;//得到数据之后page+1
						if(res.data.code == 1){							
							_self.hotList = res.data.data.data;
							
							
							console.log(_self.hotList[5].images.split(',',1))
							
							
							uni.hideNavigationBarLoading();
							uni.stopPullDownRefresh();//得到数据后停止下拉刷新
						}
					},					
				})
			},
			onNavigationBarSearchInputChanged(e) {				
				this.keywords = e.text
				this.gethotList()
				
			},
		}
	}
</script>

<style>
	
	.popup-view {
	    width: 500upx;
	}
	
	.popup-title {
	    display: block;
	    font-size: 16px;
	    line-height: 3;
	    margin-bottom: 10px;
	    text-align: center;
	}
	
	.popup-buttons button {
	    margin-left: 4px;
	    margin-right: 4px;
	}
	
	
	
	
	
	.content {
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #4F5861;
	}

	.head_button{
		display: flex;
		justify-content: space-between;
		padding: 60upx 0;
		width: 80%;
	}
	.button_item{
		text-align: center;
	}
	.button_item image{
		width: 100upx;
		height: 100upx;
		border-radius: 50%;
	}
	.button_item .button_text{
		color: white;
		font-size: 28upx;
	}
	.Popular{
		width: 100%;
		/* margin-top: -10upx; */
	}
	.pop_title{
		width: 100%;
		height: 90upx;
		text-align: center;
		font-size: 31upx;
		line-height: 90upx;
		background: white;
		border-radius: 10upx 10upx 0 0;
	}
	.pop_content{
		overflow: hidden;
		width: 100%;
		background: white;
	}
	.pop_item{
		display: flex;
		justify-content: space-between;
		padding: 20upx;
	}
	.pop_item .left{
		width: 240upx;
		height: 180upx;
	}
	.pop_item .left image{
		width: 240upx;
		height: 180upx;
	}
	.pop_item .right{
		width: 440upx;
		height: 200upx;
	}
	.pop_item .right .name{
		width: 100%;
		height: 40upx;
		font-size: 32upx;
	}
	.pop_item .right .address{
		width: 100%;
		height: 40upx;
		margin: 10upx 0;
		color: #707071;
		font-size: 24upx;
		line-height: 40upx;
	}
	.pop_item .right .tags{
		display: flex;
	}
	.pop_item .right .tag{
		padding: 0 5upx;
		margin:0 5upx;
		color: #C0C0C0;
		font-size: 24upx;
		border: solid 1px #C0C0C0;
	}
	.pop_item .right .prices{
		margin-top: 20upx;
		width: 100%;
		display: flex;
		justify-content: space-between;
	}
	.pop_item .right .prices .price{
		
		color: #FF4C4C;
		font-size: 30upx;
		line-height: 40upx;
		font-weight: bold;
	}
	.pop_item .right .prices .unprice{
		
		color: #999999;
		font-size: 30upx;
		line-height: 40upx;
		font-weight: bold;
	}
	.pop_item .right .prices .existence{
		width: 60upx;
		height: 30upx;
		background: #CCCCCC;
		color: white;
		font-size: 24upx;
		line-height: 30upx;
		text-align: center;
	}
</style>
